package com.zzu.base.scheduler;

import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.quartz.AdaptableJobFactory;
import org.springframework.stereotype.Component;

/**
 * 让Quartz Job能够使用Spring的依赖注入
 */
@Component
public class SpringBeanJobFactory extends AdaptableJobFactory implements ApplicationContextAware {

    // Spring的Bean工厂，用于手动注入依赖
    private AutowireCapableBeanFactory autowireCapableBeanFactory;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        // 获取Spring的自动注入能力Bean工厂
        this.autowireCapableBeanFactory = applicationContext.getAutowireCapableBeanFactory();
    }

    @Override
    protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
        // 1. 调用父类方法创建Job实例（Quartz默认方式）
        Object jobInstance = super.createJobInstance(bundle);

        // 2. 通过Spring的Bean工厂为Job实例注入依赖
        autowireCapableBeanFactory.autowireBean(jobInstance);

        return jobInstance;
    }
}
